﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using NLog.Extensions.Logging;
using SealManagement.Models;
using SealManagement.SqlData;

namespace SealManagement
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure<CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });
            //配置项中添加数据库连接
            //Update-Database
            //var conn = "Data Source=.;Initial Catalog=SignMigration;Integrated Security=SSPI; ";
            //services.AddDbContext<SignContext>(options => options.UseSqlServer(conn));

            services.AddDbContext<SignContext>(options =>
            {
                options.UseSqlite(Configuration.GetConnectionString("SqliteConnection"));
            });

            services.AddSingleton(provider => new RedisManager(Configuration.GetConnectionString("RedisConnection")));

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

            //
            //services.AddOptions<AppSettings>();
            services.Configure<AppSettings>(Configuration.GetSection("AppSettings"));
            //services.ConfigureWritable<AppSettings>(Configuration.GetSection("AppSettings"), "appsettings.json");

            services.Configure<FormOptions>(x =>
            {
                x.ValueLengthLimit = int.MaxValue;
                x.MultipartBodyLengthLimit = int.MaxValue; // In case of multipart
            });
            //添加身份验证模式
            services.AddAuthentication(options =>
            {
                options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            }).AddCookie(options =>
            {
                options.Cookie.Name = ".AspNetCore.GMSeal";
                options.LoginPath = "/Login/Login";
                options.AccessDeniedPath = "/Login/Denied";
            });
            //添加 缓存
            services.AddMemoryCache();
            services.AddCors(options =>
            {
                options.AddPolicy("AnyCors",
                    policy => policy.WithOrigins(Configuration["CorsOrigins"])
                        .AllowAnyHeader()
                        .AllowAnyMethod()
                        .AllowCredentials());
            });
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        //public void Configure(IApplicationBuilder app, IHostingEnvironment env,ILoggerFactory loggerFactory)
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            app.UseDeveloperExceptionPage();
            //if (env.IsDevelopment())
            //{
            //    app.UseDeveloperExceptionPage();
            //}
            //else
            //{
            //    app.UseExceptionHandler("/Home/Error");
            //    //app.UseHsts();//应用https请求
            //}
            app.UseCors("AnyCors");
            //配置项中须加入验证后的身份
            app.UseAuthentication();
            //app.UseHttpsRedirection();
            app.UseStaticFiles();
            //app.UseCookiePolicy();

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    //template: "{controller=Home}/{action=Index}/{id?}");
                    template: "{controller=Login}/{action=Login}/{id?}");
            });
            app.UseMvc(routes => {
                routes.MapRoute("blog", "blog/{*article}", defaults: new { controller = "Blog", action = "Article" });
            });
            //添加NLog
            //loggerFactory.AddNLog();
            //加入日志编码格式
            Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
        }
    }
}
